<?php
/**
 * Created by PhpStorm.
 * User: huynguyen
 * Date: 9/22/14
 * Time: 8:19 PM
 */

namespace Backend\Modules\Video\Controllers;

//use Phalcon\Paginator\Adapter\Model as Paginator;
use Phalcon\Paginator\Adapter\QueryBuilder as Paginator;
use Phalcon\Mvc\Model\Resultset;
use Library\Pagination\Pager as Pager;
use Backend\Modules\Video\Models\Video;
use Backend\Modules\Video\Models\VideoDescription;
use Backend\Modules\Video\Models\VideoCategoryLink;
use Backend\Modules\Video\Models\Artist ;
use Backend\Modules\Video\Models\VideoArtistLink;
use Backend\Modules\Video\Models\VideoGroup;
use Backend\Modules\Video\Models\VideoGroupLink;
use Backend\Modules\Video\Forms\FormCreateVideoGroup;
use Library\Upload\UploadFile as UploadFile;
use Common\library\Common;
use Library\Constant\Constant;
use Library\Utils\Slug;
use Common\Models\Videos\VideoGroupDescription;
use Backend\Modules\Video\Forms\FormSearchVideoGroup;

class VideoGroupController extends \BackendController
{
    public $urlVideoGroup = 'video/group';

    public function indexAction()
    {
        $currentPage = abs($this->request->getQuery('page', 'int', 1));
        
        $videoGroup = new VideoGroup();
        $videoGroupBuilder = $videoGroup->queryBuilderSeachVideo($this->request->get());
        $data = array();

        $formSearchVideoGroup = new FormSearchVideoGroup();
        $formSearchVideoGroup->setAction($this->getBackendUrl() . '/' . $this->urlVideoGroup);
        $formSearchVideoGroup->bind($this->request->get() , $videoGroup);

        if ($currentPage == 0) {
            $currentPage = 1;
        }
        $pager = new Pager(
            new Paginator(array(
                'builder'  => $videoGroupBuilder,
                'limit' => Constant::ITEM_PER_PAGE_20,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                // Range window will be 5 pages
                'rangeLength' => 5,
                // Just a string with URL mask
                'urlMask'     => '',
            )
        );
        
        $this->view->formSearchVideoGroup = $formSearchVideoGroup;
        $this->view->pager = $pager;
    }
    /*
     * creat group video
     */
    public function createAction()
    {
        $this->assets
        ->addJs('vendor/backend/js/video/video_category_ajax.js');

        $uploadFile = new UploadFile();

        $form = new FormCreateVideoGroup();

        if($this->request->isPost())
        {
            if($form->isValid($this->request->getPost()) != false)
            {
                $videoGroup = new VideoGroup();
                $videoGroup->assign(array(
                    'slug' => Slug::generate($this->request->getPost('name_vn')),
                    'total_episode' => $this->request->getPost('total_episode'),
                    'is_vip' => 'N',//$this->request->getPost('is_vip'),
                    'hot_month'             => $this->request->getPost('status' , 'int'),
                    'created_user'          => 1,//$this->request->getPost('status', 'int'),
                    'published_user'        => 1,//$this->request->getPost('status', 'int'),
                    'created_time'          => date('Y-m-d h:m:s'),
                    'updated_time'          => date('Y-m-d h:m:s'),
                    'ip_address'            => '0',
                    'status'=> 'W' ,  //$this->request->getPost('status')
                ));
                if($videoGroup->save())
                {
                    $videoDescription = new VideoDescription();
                    $videoDescription->assign(array(
                        'video_group_id'  => $videoGroup->getId(),
                        'name'      => $this->request->getPost('name'),
                        'name_vn'      => $this->request->getPost('name_vn'),
                        'short_name'      => $this->request->getPost('short_name'),
                        'national_id'           => $this->request->getPost('national_id'),
                        'year_product'          => $this->request->getPost('year_product'),
                        'year_publish'          => $this->request->getPost('year_publish'),
                        'description'   => $this->request->getPost('description'),
                    ));
                    $videoDescription->save();

                    $videoCategoriesId = $this->request->getPost('category_id');
                    if($videoCategoriesId)
                    {
                        foreach($videoCategoriesId as $videoCategoryId)
                        {
                            $checkCategoryHaveCategoryLink = VideoCategoryLink::find(array(
                                "video_group_id = " . $videoGroup->getId() . " AND category_id = $videoCategoryId"
                            ))->count();

                            if($checkCategoryHaveCategoryLink <= 0){
                                $videoLink = new VideoCategoryLink();
                                $videoLink->assign(array(
                                    'video_group_id'  => $videoGroup->getId(),
                                    'category_id'      => $videoCategoryId,
                                    'position'      => 0,
                                ));
                                $videoLink->save();
                            }
                        }
                    }

                    $videoGroupLink = new VideoCategoryLink();
                    $videoGroupLink->assign(array(
                        'video_group_id'  => $videoGroup->getId(),
                        'category_id'      => $this->request->getPost('category_id'),
                        'position'      => 0,
                    ));
                    $videoGroupLink->save();

                    //Check if the user has uploaded files
                    if ($this->request->hasFiles() == true) {
                        if ($this->request->hasFiles() == true) {
                            //Print the real file names and their sizes
                            $uploadFile->doUpload(array('folder_upload' => 'files' , 'object_id' => $videoGroup->getId() , 'image_id' => 0 , 'object_type' => 'video_group' , 'type' => 'M' , 'position' => 0) , Common::listThumbnailOptionA());
                        }
                    }

                    return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideoGroup);
                }
                $this->flash->error($videoGroup->getMessages());
            }
        }
        $this->view->form = $form;
    }

    public function editAction($id)
    {
         $this->assets
        ->addJs('vendor/backend/js/video/video_category_ajax.js');

        $uploadFile = new UploadFile();
        $this->assets
            ->addJs('vendor/backend/js/video/video_ajax.js')
            ->addJs('vendor/backend/js/video/video_group.js');

        $videoGroup = VideoGroup::findFirstById($id);

        $videoDescription = VideoDescription::find(array(
            "video_group_id = $id"
        ))->getFirst();
        //$videoCategoryLink = VideoCategoryLink::findFirst("video_group_id = $id");

        if(!$videoGroup || !$videoDescription)
        {
            $this->flash->error("Video group was not found");
            return $this->dispatcher->forward(array(
                'action' => 'index'
            ));
        }
        $form = new FormCreateVideoGroup($videoGroup , array('edit' => true));
        $formDescription = new FormCreateVideoGroup($videoDescription , array('edit' => true));
        //$formCategoryLink = new FormCreateVideoGroup($videoCategoryLink , array('edit' => true));
        $form->setAction($this->getBackendUrl() . '/' . $this->urlVideoGroup . '/edit/' . $id);

        $tab = $this->request->get('tab') ? $this->request->get('tab') : 'general';

        if($this->request->getPost())
        {
            switch($tab)
            {
                case 'general':
                    if($form->isValid($this->request->getPost()) != false)
                    {
                        $videoGroup->assign(array(
                            //'slug' => Slug::generate($this->request->getPost('name_vn')),
                            'total_episode' => $this->request->getPost('total_episode'),
                            'is_vip' => 'N',
                            'hot_month'             => 'N',
                            'created_user'          => 1,
                            'published_user'        => 1,
                            'created_time'          => date('Y-m-d h:m:s'),
                            'updated_time'          => date('Y-m-d h:m:s'),
                            'ip_address'            => '0',
                            'status'=> 'W',//$this->request->getPost('status')
                        ));

                        if($videoGroup->save())
                        {

                            $videoDescription->assign(array(
                                'video_group_id'  => $videoGroup->getId(),
                                'name'      => $this->request->getPost('name'),
                                'name_vn'      => $this->request->getPost('name'),
                                'short_name'      => $this->request->getPost('short_name'),
                                'national_id'           => $this->request->getPost('national_id'),
                                'year_product'          => $this->request->getPost('year_product'),
                                'year_publish'          => $this->request->getPost('year_publish'),
                                'description'   => $this->request->getPost('description'),
                            ));
                            $videoDescription->save();

                            $videoCategoryLinksDelete = VideoCategoryLink::find(array(
                                "video_group_id = " . $videoGroup->getId()
                            ));

                            if($videoCategoryLinksDelete)
                            {
                                foreach ($videoCategoryLinksDelete as $videoCategoryLinks) {
                                    if($videoCategoryLinks){
                                        $videoCategoryLinks->delete();  
                                    }
                                }
                            }

                            $videoCategoriesId = $this->request->getPost('category_id');
                            
                            if($videoCategoriesId)
                            {
                                try {
                                    foreach($videoCategoriesId as $videoCategoryId)
                                    {
                                        $checkCategoryHaveCategoryLink = VideoCategoryLink::find(array(
                                            "video_group_id = " . $id . " AND category_id = $videoCategoryId"
                                        ))->count();

                                        if($checkCategoryHaveCategoryLink <= 0){
                                            $videoLink = new VideoCategoryLink();
                                            $videoLink->assign(array(
                                                'video_group_id'  => $videoGroup->getId(),
                                                'category_id'      => $videoCategoryId,
                                                'position'      => 0,
                                            ));
                                            $videoLink->save();
                                        }
                                    }
                                } catch (Exception $e) {
                                   echo $e->getMessage();
                                   echo $e->getTraceAsString();
                                }
                            }

                            //Check if the user has uploaded files
                            if ($this->request->hasFiles() == true) {
                                if ($this->request->hasFiles() == true) {
                                    $uploadFile->doUpload(array('folder_upload' => 'files' , 'object_id' => $videoGroup->getId() , 'image_id' => 0 , 'object_type' => 'video_group' , 'type' => 'M' , 'position' => 0) , Common::listThumbnailOptionA());
                                }
                            }

                            return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideoGroup);
                        }

                        $this->flash->error($videoGroup->getMessages());
                    }
                    else{
                        die(print_r($form->getMessages()));
                    }
                    break;

                case 'album':
                    if ($this->security->checkToken()) {
                        if ($this->request->hasFiles() == true) {
                            $paramUpload = array(
                                'folder_upload' => 'files' ,
                                'object_id' => $videoGroup->getId() ,
                                'object_type' => 'video_group' ,
                                'type' => 'A' ,
                                'position' => 0
                            );
                            $uploadFile->doUpload($paramUpload , Common::listThumbnailOptionA());
                        }
                    }
                    break;

                case 'actor':
                case 'director':

                    if($this->request->hasPost('selectArtistRemove'))
                    {
                        $selectedVideos = $this->request->getPost('selectArtistRemove');
                        $data = array();
                        foreach($selectedVideos as $artistId)
                        {
                            $videoArtistLink = VideoArtistLink::find(array(
                                "video_group_id = $id AND artist_id = $artistId"
                            ))->getFirst();
                            if($videoArtistLink)
                            {
                                $videoArtistLink->delete();
                            }
                        }
                    }

                    break;

                case 'video':
                    if($this->request->hasPost('selectVideo'))
                    {
                        $selectVideos = $this->request->getPost('selectVideo');
                        $data = array();
                        foreach($selectVideos as $videoId)
                        {
                            $checkVideoHaveVideoGroup = VideoGroupLink::find(array(
                                "video_id = $videoId AND video_group_id = $id"
                            ))->count();

                            if($checkVideoHaveVideoGroup <= 0)
                            {
                                $selectVideo = Video::findFirstById($videoId);
                                if($selectVideo)
                                {
                                    $videoGroupLink = new VideoGroupLink();
                                    $videoGroupLink->setVideoId($videoId);
                                    $videoGroupLink->setVideoGroupId($id);
                                    $videoGroupLink->setPosition(0);
                                    $videoGroupLink->save();
                                }
                            }
                        }
                    }

                    if($this->request->hasPost('selectedVideoRemove'))
                    {
                        $selectedVideos = $this->request->getPost('selectedVideoRemove');
                        $data = array();
                        foreach($selectedVideos as $videoId)
                        {
                            $videoGroupLink = VideoGroupLink::find(array(
                                "video_id = $videoId AND video_group_id = $id"
                            ))->getFirst();
                            if($videoGroupLink)
                            {
                                $videoGroupLink->delete();
                            }
                        }
                    }

                    if($this->request->hasPost('video'))
                    {
                        $videos = $this->request->getPost('video');
                        $positions = $videos['position'];
                        foreach($positions as $videoId => $value)
                        {
                            if((int)$value > 0)
                            {
                                $videoGroupLink = VideoGroupLink::find(array(
                                    "video_id = $videoId AND video_group_id = $id"
                                ))->getFirst();
                                $videoGroupLink->setPosition($value);
                                if(!$videoGroupLink->save())
                                {
                                    $this->flash->error($videoGroupLink->getMessages());
                                }
                            }
                        }
                    }
                    break;

            }
            return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideoGroup . '/edit/' . $id . '?tab=' . $tab);
        }
        $this->view->tab = $tab;
        $this->view->form = $form;
        $this->view->formDescription = $formDescription;

        $this->view->videoCategoryLinks = VideoCategoryLink::find(array(
            "video_group_id = $id"
        ));
        $this->view->videoGroup = $videoGroup;
        $this->view->videoGroupLinks = VideoGroupLink::find(array(
            "video_group_id = $id",
            "order" => "position"
        ));

        $this->view->videoActorLinks = $this->modelsManager->createBuilder()
            ->from(array('videoArtistLink' => '\Backend\Modules\Video\Models\VideoArtistLink'))
            ->groupBy("videoArtistLink.artist_id")
            ->join('\Backend\Modules\Video\Models\Artist' , 'videoArtistLink.artist_id = artist.id' , 'artist')
            ->limit(Constant::ITEM_PER_PAGE_20)
            ->where('artist.artist_type = :artist_type: AND videoArtistLink.video_group_id = :video_group_id:', array('artist_type' => Artist::ACTOR , 'video_group_id' => $id))
            ->orderBy('videoArtistLink.artist_id')
            ->getQuery()
            ->execute();


        $this->view->videoDirectorLinks = $this->modelsManager->createBuilder()
            ->from(array('videoArtistLink' => '\Backend\Modules\Video\Models\VideoArtistLink'))
            ->groupBy("videoArtistLink.artist_id")
            ->join('\Backend\Modules\Video\Models\Artist' , 'videoArtistLink.artist_id = artist.id' , 'artist')
            ->limit(Constant::ITEM_PER_PAGE_20)
            ->where('artist.artist_type = :artist_type: AND videoArtistLink.video_group_id = :video_group_id:', array('artist_type' => Artist::DIRECTOR , 'video_group_id' => $id))
            ->orderBy('videoArtistLink.artist_id')
            ->getQuery()
            ->execute();
    }

    /*
     * Delete video group
     */

    public function deleteAction($id)
    {
        $videoGroup = VideoGroup::findFirstById($id);
        if(!$videoGroup)
        {
            $this->flash->error("Video was not found");
            return $this->dispatcher->forward(array(
                'action' => 'index'
            ));
        }
        if(!$videoGroup->delete())
        {
            $this->flash->error($videoGroup->getMessages());
        }
        else
        {
            $this->flash->success("Video was deleted");
        }

        return $this->dispatcher->forward(array(
            'action' => 'index'
        ));
    }

    /*
    * Update video group
    */

    public function updateStatusAction()
    {
        $videoGroupId = $this->request->get('video_group_id' , 'int');
        $status = $this->request->get('status');
        if($videoGroupId > 0)
        {
            $videoGroup = VideoGroup::findFirstById($videoGroupId);
            if($videoGroup)
            {
                $videoGroup->setStatus($status);
                $videoGroup->save();
                $this->flash->success("Video update success");
            }
            else
            {
                $this->flash->error($videoGroup->getMessages());
            }

            return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideoGroup);
        }
    }
}
